package com.rc.web.service.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rc.pojo.vo.poi.PoiResultVo;
import com.rc.web.utils.VivoAuth;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Service
public class PoiService {
    private static final String appId = "2025985389";
    private static final String appKey = "eAkRKtYXOawsmtVv";
    private static final String method = "GET";
    private static final String domain = "api-ai.vivo.com.cn";
    private static final String uri = "/search/geo";

    public PoiResultVo searchPoi(String keywords, String city, int pageNum, int pageSize) throws UnsupportedEncodingException, JsonProcessingException {
        // 请求参数
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("keywords", keywords);
        queryMap.put("city", city);
        queryMap.put("page_num", pageNum);
        queryMap.put("page_size", pageSize);
        
        // 将请求参数拼接成url查询字符串
        String query = mapToQueryString(queryMap);
        HttpHeaders headers = VivoAuth.generateAuthHeaders(appId, appKey, method, uri, query);
        String url = String.format("http://%s%s?%s", domain, uri, query);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> resp = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        System.out.println(String.format("response status: %s", resp.getStatusCode()));

        // 使用Jackson进行JSON转换
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(resp.getBody(), PoiResultVo.class);
    }

    public static String mapToQueryString(Map<String, Object> map) {
        if (map.isEmpty()) {
            return "";
        }
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (queryStringBuilder.length() > 0) {
                queryStringBuilder.append("&");
            }
            queryStringBuilder.append(entry.getKey());
            queryStringBuilder.append("=");
            queryStringBuilder.append(entry.getValue());
        }
        return queryStringBuilder.toString();
    }
}
